var checkMediaAuth = function(callback) {
  wx.getSetting({
    success: (res) => {
      let camera = res.authSetting['scope.camera']
      let record = res.authSetting['scope.record']
      if(camera && record) {
        callback(true, true)
      } else {
        _requestMediaAuth(callback)
      }
    },
    fail: (res) => {
      callback(false, false)
    }
  })
}

var _requestMediaAuth = function(callback) {
  _getAuthorize({
    scope: 'scope.camera',
    authorizeName: "摄像头",
    success: function (res) {
      _getAuthorize({
        scope: 'scope.record',
        authorizeName: "录音",
        success: function (res) {
          console.log("record authorize ,res =", res)
          callback(true, true)
        },
        fail : function() {
          callback(true, false)
        }
      })
    }, 
    fail : function() {
      callback(false, false)
    }
  })
}

//权限获取
//@params scope 权限
//@params authorizeName 权限名称
var _getAuthorize = function(data) {
  var that = this;
  wx.authorize({
    scope: data.scope,
    success: data.success, //授权成功
    fail: res => {
      //弹窗--是否去开启对应权限
      wx.showModal({
        title: '提示',
        content: '您未授权' + data.authorizeName + "，功能将无法使用",
        showCancel: true,
        confirmText: "去授权",
        confirmColor: "#4097ff",
        success: function (res) {
          if (!res.confirm) {
            console.log("no authorize = ", data.scope, "cancel is ", res.cancel, "conform is ", res.confirm, res)
            data.fail()
            return
          }

          //打开--授权页面
          wx.openSetting({
            fail: function () {
              data.fail()
            },

            success: function (res) {
              //打开授权设置后，用户还是未授权
              if (!res.authSetting[data.scope]) {
                data.fail()
                return
              }
              //授权成功的
                data.success()
            }
          })

        }
      })
    }
  })
}

module.exports = {
  checkMediaAuth: checkMediaAuth,
};